{% extends "pc/template.html" %}

{% block title %}
商品分类列表
{% endblock %}

{% include 'pc/公共样式配置/CSS总样式.html' %}

{% block css %}
<link rel="stylesheet" href="/static/HubUI/css/sweetalert2.css">
<style>
    .card {
        margin: 1rem 0;
    }
    .table-responsive {
        margin: 0;
    }
    .action-buttons .btn {
        padding: 0.25rem 0.5rem;
        margin: 0 0.2rem;
    }
    .sub-category-row {
        background-color: #f8f9fa;
    }
    .sub-category-row td:first-child {
        padding-left: 3rem;
    }
    .status-badge {
        padding: 0.35em 0.65em;
        font-size: 0.75em;
        font-weight: 700;
        border-radius: 0.25rem;
    }
    .status-normal {
        background-color: #e8fff3;
        color: #28c76f;
    }
    .status-disabled {
        background-color: #ffe4e4;
        color: #ea5455;
    }
    .status-maintenance {
        background-color: #fff4e5;
        color: #ff9f43;
    }
    .category-toggle {
        cursor: pointer;
        color: #566a7f;
        transition: transform 0.2s;
    }
    .category-toggle.collapsed {
        transform: rotate(-90deg);
    }
    .sub-categories {
        transition: all 0.3s ease;
    }
    .sub-categories.collapsed {
        display: none;
    }
    .remark-text {
        display: inline-block;
        max-width: 150px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        cursor: help;
        vertical-align: middle;
    }
    .sub-category-table {
        margin-bottom: 0;
        width: 100%;
    }
    .sub-category-table td {
        padding: 0.75rem;
    }
    .table td {
        max-width: 200px;
        overflow: hidden;
    }
    .table td:nth-child(4) {
        max-width: 150px;
    }
    .table td:nth-child(2) {
        max-width: 120px;
    }
    .table td:nth-child(1) {
        max-width: 80px;
    }
    .table td:nth-child(3) {
        max-width: 100px;
    }
    .table td:nth-child(5) {
        max-width: 100px;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <!-- 主分类卡片 -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">商品分类列表</h5>
            <div>
                <button type="button" class="btn btn-primary me-2" onclick="showAddMainCategoryModal()">
                    <i class="bx bx-plus"></i> 添加主分类
                </button>
                <button type="button" class="btn btn-success" onclick="showAddSubCategoryModal()">
                    <i class="bx bx-plus"></i> 添加次分类
                </button>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>名称</th>
                            <th>状态</th>
                            <th>备注</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="categoryTableBody">
                        <!-- 分类数据将通过JavaScript动态加载 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- 添加主分类模态框 -->
    <div class="modal fade" id="addMainCategoryModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加主分类</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addMainCategoryForm">
                        <div class="mb-3">
                            <label class="form-label" for="mainCategoryName">分类名称</label>
                            <input type="text" class="form-control" id="mainCategoryName" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="mainCategoryStatus">状态</label>
                            <select class="form-select" id="mainCategoryStatus" name="status">
                                <option value="1">正常</option>
                                <option value="2">禁用</option>
                                <option value="3">临时维护</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addMainCategory()">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加次分类模态框 -->
    <div class="modal fade" id="addSubCategoryModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加次分类</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="addSubCategoryForm">
                        <div class="mb-3">
                            <label class="form-label" for="parentCategory">主分类</label>
                            <select class="form-select" id="parentCategory" name="parent" required>
                                <!-- 主分类选项将通过JavaScript动态加载 -->
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="subCategoryName">分类名称</label>
                            <input type="text" class="form-control" id="subCategoryName" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="subCategoryStatus">状态</label>
                            <select class="form-select" id="subCategoryStatus" name="status">
                                <option value="1">正常</option>
                                <option value="2">禁用</option>
                                <option value="3">临时维护</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="addSubCategory()">添加</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 编辑分类模态框 -->
    <div class="modal fade" id="editCategoryModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑分类</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editCategoryForm">
                        <input type="hidden" id="editCategoryId">
                        <input type="hidden" id="editCategoryType">
                        <div class="mb-3" id="editParentCategoryGroup">
                            <label class="form-label" for="editParentCategory">主分类</label>
                            <select class="form-select" id="editParentCategory" name="parent">
                                <!-- 主分类选项将通过JavaScript动态加载 -->
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="editCategoryName">分类名称</label>
                            <input type="text" class="form-control" id="editCategoryName" name="name" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="editCategoryStatus">状态</label>
                            <select class="form-select" id="editCategoryStatus" name="status">
                                <option value="1">正常</option>
                                <option value="2">禁用</option>
                                <option value="3">临时维护</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="editCategoryRemark">备注</label>
                            <textarea class="form-control" id="editCategoryRemark" name="remark" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="updateCategory()">保存</button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
    // 页面加载完成后获取分类列表
    document.addEventListener('DOMContentLoaded', function() {
        getCategoryList();
    });

    // 获取分类列表
    function getCategoryList() {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        Promise.all([
            axios.get('/api/category/get_category_list/'),
            axios.get('/api/category/get_category_sub_list/')
        ]).then(function([mainResponse, subResponse]) {
            if (mainResponse.data.code === 200 && subResponse.data.code === 200) {
                renderCategoryTable(mainResponse.data.data, subResponse.data.data);
                // 更新主分类下拉选项
                updateMainCategoryOptions(mainResponse.data.data);
            } else {
                Swal.fire('错误', '获取分类列表失败', 'error');
            }
        }).catch(function(error) {
            Swal.fire('错误', '获取分类列表失败', 'error');
        }).finally(function() {
            loadingToast.close();
        });
    }

    // 渲染分类表格
    function renderCategoryTable(mainCategories, subCategories) {
        const tbody = document.getElementById('categoryTableBody');
        tbody.innerHTML = '';

        mainCategories.forEach(mainCategory => {
            // 添加主分类行
            const mainTr = document.createElement('tr');
            mainTr.innerHTML = `
                <td>
                    <i class="bx bx-chevron-down category-toggle" onclick="toggleSubCategories(${mainCategory.id})"></i>
                    ${mainCategory.id}
                </td>
                <td>${mainCategory.name}</td>
                <td>
                    <span class="status-badge ${getStatusClass(mainCategory.status)}">
                        ${getStatusText(mainCategory.status)}
                    </span>
                </td>
                <td>
                    <div class="remark-text" title="${mainCategory.remark || '-'}">
                        ${mainCategory.remark || '-'}
                    </div>
                </td>
                <td class="action-buttons">
                    <button class="btn btn-sm btn-info" onclick="editCategory(${mainCategory.id}, 'main')">
                        <i class="bx bx-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="deleteCategory(${mainCategory.id}, 'main')">
                        <i class="bx bx-trash"></i>
                    </button>
                </td>
            `;
            tbody.appendChild(mainTr);

            // 创建次分类容器
            const subCategoriesContainer = document.createElement('tr');
            subCategoriesContainer.id = `sub-categories-${mainCategory.id}`;
            subCategoriesContainer.className = 'sub-categories';
            const subCategoriesCell = document.createElement('td');
            subCategoriesCell.colSpan = 5;
            subCategoriesCell.style.padding = '0';
            
            // 创建次分类表格
            const subTable = document.createElement('table');
            subTable.className = 'sub-category-table';
            
            // 添加该主分类下的次分类行
            const subCategoriesOfMain = subCategories.filter(sub => sub.parent === mainCategory.id);
            subCategoriesOfMain.forEach(subCategory => {
                const subTr = document.createElement('tr');
                subTr.className = 'sub-category-row';
                subTr.innerHTML = `
                    <td>${subCategory.id}</td>
                    <td>${subCategory.name}</td>
                    <td>
                        <span class="status-badge ${getStatusClass(subCategory.status)}">
                            ${getStatusText(subCategory.status)}
                        </span>
                    </td>
                    <td>
                        <div class="remark-text" title="${subCategory.remark || '-'}">
                            ${subCategory.remark || '-'}
                        </div>
                    </td>
                    <td class="action-buttons">
                        <button class="btn btn-sm btn-info" onclick="editCategory(${subCategory.id}, 'sub')">
                            <i class="bx bx-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteCategory(${subCategory.id}, 'sub')">
                            <i class="bx bx-trash"></i>
                        </button>
                    </td>
                `;
                subTable.appendChild(subTr);
            });
            
            subCategoriesCell.appendChild(subTable);
            subCategoriesContainer.appendChild(subCategoriesCell);
            tbody.appendChild(subCategoriesContainer);
        });
    }

    // 切换次分类显示/隐藏
    function toggleSubCategories(mainCategoryId) {
        const toggleIcon = document.querySelector(`.category-toggle[onclick="toggleSubCategories(${mainCategoryId})"]`);
        const subCategories = document.getElementById(`sub-categories-${mainCategoryId}`);
        
        toggleIcon.classList.toggle('collapsed');
        subCategories.classList.toggle('collapsed');
    }

    // 获取状态样式类
    function getStatusClass(status) {
        switch (parseInt(status)) {
            case 1:
                return 'status-normal';
            case 2:
                return 'status-disabled';
            case 3:
                return 'status-maintenance';
            default:
                return 'status-normal';
        }
    }

    // 获取状态文本
    function getStatusText(status) {
        switch (parseInt(status)) {
            case 1:
                return '正常';
            case 2:
                return '禁用';
            case 3:
                return '临时维护';
            default:
                return '正常';
        }
    }

    // 更新主分类下拉选项
    function updateMainCategoryOptions(mainCategories) {
        const parentSelect = document.getElementById('parentCategory');
        const editParentSelect = document.getElementById('editParentCategory');
        const options = mainCategories.map(category => 
            `<option value="${category.id}">${category.name}</option>`
        ).join('');
        
        parentSelect.innerHTML = options;
        editParentSelect.innerHTML = options;
    }

    // 显示添加主分类模态框
    function showAddMainCategoryModal() {
        const modal = new bootstrap.Modal(document.getElementById('addMainCategoryModal'));
        document.getElementById('addMainCategoryForm').reset();
        modal.show();
    }

    // 显示添加次分类模态框
    function showAddSubCategoryModal() {
        const modal = new bootstrap.Modal(document.getElementById('addSubCategoryModal'));
        document.getElementById('addSubCategoryForm').reset();
        modal.show();
    }

    // 添加主分类
    function addMainCategory() {
        const form = document.getElementById('addMainCategoryForm');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());
        data.status = parseInt(data.status);

        // 立即关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('addMainCategoryModal'));
        modal.hide();

        const loadingToast = Swal.fire({
            title: '添加中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.post('/api/category/create_category/', data)
            .then(function(response) {
                if (response.data.code === 200) {
                    Swal.fire({
                        icon: 'success',
                        title: '成功',
                        text: '主分类添加成功',
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        getCategoryList();
                    });
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '添加主分类失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 添加次分类
    function addSubCategory() {
        const form = document.getElementById('addSubCategoryForm');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());
        data.status = parseInt(data.status);

        // 立即关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('addSubCategoryModal'));
        modal.hide();

        const loadingToast = Swal.fire({
            title: '添加中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        axios.post('/api/category/create_category_sub/', data)
            .then(function(response) {
                if (response.data.code === 200) {
                    Swal.fire({
                        icon: 'success',
                        title: '成功',
                        text: '次分类添加成功',
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        getCategoryList();
                    });
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '添加次分类失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 编辑分类
    function editCategory(categoryId, type) {
        const loadingToast = Swal.fire({
            title: '加载中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        const url = type === 'main' ? 
            `/api/category/get_category/${categoryId}/` :
            `/api/category/get_category_sub/${categoryId}/`;

        axios.get(url)
            .then(function(response) {
                if (response.data.code === 200) {
                    const category = response.data.data;
                    document.getElementById('editCategoryId').value = categoryId;
                    document.getElementById('editCategoryType').value = type;
                    document.getElementById('editCategoryName').value = category.name;
                    document.getElementById('editCategoryStatus').value = category.status;
                    document.getElementById('editCategoryRemark').value = category.remark || '';

                    // 显示/隐藏主分类选择
                    const parentGroup = document.getElementById('editParentCategoryGroup');
                    if (type === 'sub') {
                        parentGroup.style.display = 'block';
                        document.getElementById('editParentCategory').value = category.parent;
                    } else {
                        parentGroup.style.display = 'none';
                    }

                    const modal = new bootstrap.Modal(document.getElementById('editCategoryModal'));
                    modal.show();
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '获取分类信息失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 更新分类
    function updateCategory() {
        const categoryId = document.getElementById('editCategoryId').value;
        const type = document.getElementById('editCategoryType').value;
        const form = document.getElementById('editCategoryForm');
        const formData = new FormData(form);
        const data = Object.fromEntries(formData.entries());

        // 立即关闭模态框
        const modal = bootstrap.Modal.getInstance(document.getElementById('editCategoryModal'));
        modal.hide();

        const loadingToast = Swal.fire({
            title: '更新中...',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        const url = type === 'main' ?
            `/api/category/update_category/${categoryId}/` :
            `/api/category/update_category_sub/${categoryId}/`;

        axios.post(url, data)
            .then(function(response) {
                if (response.data.code === 200) {
                    Swal.fire({
                        icon: 'success',
                        title: '成功',
                        text: '分类更新成功',
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        getCategoryList();
                    });
                } else {
                    Swal.fire('错误', response.data.msg, 'error');
                }
            })
            .catch(function(error) {
                Swal.fire('错误', '更新分类失败', 'error');
            })
            .finally(function() {
                loadingToast.close();
            });
    }

    // 删除分类
    function deleteCategory(categoryId, type) {
        Swal.fire({
            title: '确认删除',
            text: '确定要删除这个分类吗？',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }).then((result) => {
            if (result.isConfirmed) {
                const loadingToast = Swal.fire({
                    title: '删除中...',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                const url = type === 'main' ?
                    `/api/category/delete_category/${categoryId}/` :
                    `/api/category/delete_category_sub/${categoryId}/`;

                axios.delete(url)
                    .then(function(response) {
                        if (response.data.code === 200) {
                            Swal.fire({
                                icon: 'success',
                                title: '成功',
                                text: '分类删除成功',
                                showConfirmButton: false,
                                timer: 1500
                            }).then(() => {
                                getCategoryList();
                            });
                        } else {
                            Swal.fire('错误', response.data.msg, 'error');
                        }
                    })
                    .catch(function(error) {
                        Swal.fire('错误', '删除分类失败', 'error');
                    })
                    .finally(function() {
                        loadingToast.close();
                    });
            }
        });
    }
</script>
{% endblock %}

{% block nav_left %}
{% include "pc/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% include 'pc/公共样式配置/JS总样式.html' %}

{% block footer %}
    {% include "pc/components/Footer.html" %}
{% endblock %}